<script setup lang="ts">
import * as Api from '@/api/audio.js'
import { ref, onMounted } from 'vue';
import {Upload} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
const products = ref([])
const page =ref(1)
const pageSize =ref(100)
const form = ref({
  audio :'',
  audioTitle: '', //调查问卷链接
})
const dialogVisible = ref(false)
const audioBase64 = ref(null);
const loading = ref(true)
const error = ref(null);
// 定义一个异步函数来获取商品列表
const fetchProducts = async () => {
  try {
    // const response = await axios.get('http://your-backend-api/products');
    // products.value = response.data;
  } catch (err) {
    error.value = '加载商品列表时出错';
  } finally {
    loading.value = false
  }
};
// 在组件挂载时调用 fetchProducts 函数

const getData =async ()=> {
  let result = await Api.list({
    "pageSize": pageSize.value,
    "page": page.value,
  })
  if (result.code === 200){
    products.value = result.data.rows
  }
}
onMounted(async () => {
  await fetchProducts()
  await getData()
})
import { ElLoading } from 'element-plus'
const url = ref("")
const fullscreenLoading = ref(false)
const add = async () => {
  let result = await Api.add({
    "audioTitle" :  form.value.audioTitle,
    "audio":url.value ,
  })
  if(result.code === 200){
    await getData()
    dialogVisible.value=false
    fullscreenLoading.value = false
    ElMessage.success(result.message)
  }else {
    fullscreenLoading.value = false
    ElMessage.error(result.message)
  }
}

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('你您确定要取消操作?')
      .then(() => {
        done()
      })
      .catch(() => {
        // catch error
      })
}
const submit = async ()=> {
  await openFullScreen1()
  add()
}
const btuAdd =() => {
  dialogVisible.value = true
}
const dele = async (id) => {
  try {
    let result = await Api.dele(id); // 假设 Api.dele 返回一个 Promise
    if (result.code === 200) {
      // 如果需要立即更新本地列表，取消注释下一行
      updateLocalProducts(id); // 一个假设的函数，用于更新本地商品列表
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('删除商品时出错:', error);
    ElMessage.error('删除商品时出错，请稍后再试。');
  }
};
const file = ref(null);
const isfile = ref(false)
const handleFileUpload = (event) => {
   file.value = event.target.files[0];
   isfile.value = true
   uploadFile()
};

const isAudio = ref(false)
const formData = new FormData();
const uploadFile = async () => {
  if (!file.value) {
    alert('请选择文件！');
    return;
  }
  const formData = new FormData();
  formData.append('file', file.value);
  try {
    const response = await Api.upload( formData)
    if (response.code === 200){
       url.value = response.message
    }
    await getData()
  } catch (error) {
    ElMessage.error('上传失败:', error);
  }
};
function logProduct(product) {
  isAudio.value = true
}
const selectedProducts = ref([]); // 选中商品的 ID 数组
console.log(selectedProducts.value)

// 删除选中商品
async function deleteSelectedProducts() {
  try {
    for (const productId of selectedProducts.value) {
      await ElMessageBox.confirm('您确定要删除吗', '温馨提示', {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(async () => {
        await dele(productId); // 等待每个删除操作完成
      })
      selectedProducts.value = []; // 清空选中状态
    }
    selectedProducts.value = []; // 清空选中状态
    // 可选：显示成功消息或执行其他成功后的逻辑
    ElMessage.success('已删除选中的商品。');
  } catch (error) {
    console.error('删除选中商品时出错:', error);
    // 重置选中状态或给用户一个错误提示（这里已经由 dele 函数内的 catch 块处理了单个删除的错误）
  }
}
// 假设的更新本地商品列表的函数（如果需要的话）
function updateLocalProducts(id) {
  products.value = products.value.filter(product => product.id !== id);
}
const title = ref('')
//查询
console.log(title.value)
const find = async (title) => {
  let result = await Api.find(title)
  console.log(title)
  if(result.code === 200){
    ElMessage.success(result.message)
    products.value = result.data
  }else {
    ElMessage.error(result.message)
  }
}
const findad = () => {
  find(title.value)
}
const fanhui = async () => {
  loading.value = true
  await getData()
  await fetchProducts()
  title.value = ''
}
const openFullScreen1 = () => {
  fullscreenLoading.value = true
  setTimeout(() => {
    fullscreenLoading.value = false
  }, 2000)
}
const isLoading = ref(true);
</script>

<template>
  <div  style="position: absolute;top: 60px;width: 90%;height: 60px;border-bottom: solid 1px rgb(221.7, 222.6, 224.4);margin: auto;padding-top: 20px;border-bottom: rgb(221.7, 222.6, 224.4) 1px solid">
    <el-row>
      <el-col :span="6">
        <el-button style="
        border: solid 1px #4285F4;
        border-radius: 20px;
        width: 150px;
        color: #4285F4;
        background-color:rgb(216.8, 235.6, 255);"
                   @click="btuAdd"
        >
          上传听力音频<el-icon class="el-icon--right"><Upload /></el-icon>
        </el-button>
        <button style="
        border: solid 1px rgb(196, 86.4, 86.4);
        border-radius: 20px;
        width: 150px;
        height: 32px;
        color: rgb(196, 86.4, 86.4);
        margin-left: 10px;
        background-color:rgb(254, 240.3, 240.3);"
            @click="deleteSelectedProducts">删除选中</button>
        <div class="grid-content ep-bg-purple" />
      </el-col>
      <el-col :span="10">
        <div class="grid-content ep-bg-purple-light" />
<!--        <audio  :src="audioSrc" controls-->
<!--               style="-->
<!--               width: 600px;-->
<!--               height: 40px;-->
<!--               background-color:#F6F7FC!important;-->
<!--               opacity: 0.8;-->
<!--               margin-bottom: 50px;-->
<!--                      "-->
<!--        ></audio>-->
      </el-col>
      <el-col :span="8">
        <el-input
            style="width: 200px;padding-left: 5px;border-radius: 20px ;margin-right: 5px;margin-left: 200px"
            placeholder="请输入名称"
            v-model="title"
        />
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="findad">
          <el-icon class="el-icon--right"><el-icon><Search /></el-icon></el-icon>
        </el-button>
        <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 50px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);"@click="fanhui">
          刷新
        </el-button>
        <div class="grid-content ep-bg-purple" />
      </el-col>
    </el-row>
  </div>
  <div style="margin-top: 60px" >
    <el-scrollbar height="670px;" >
      <div style="width: 100%;height: 665px" class="product-list" >
        <div v-if="loading" style="height: 100%;">
          <el-table v-loading="loading"  style="width: 100%;height: 100%;background-color:#F6F7FC!important;">
          </el-table>
        </div>
        <div v-else-if="error">{{ error }}</div>
        <div v-else class="product-grid" >
          <div @click="logProduct(product)" v-for="product in products" :key="product.id" class="product-box" >
            <input
                type="checkbox"
                v-model="selectedProducts"
                :value="product.id"
                style="margin-left: 130px"
            />
            <h2 style="position: relative;top: 150px;font-size: 0.9rem;">{{ product.audioTitle }}</h2>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
<!--</div>-->
  <el-dialog
      v-model="dialogVisible"
      title= '新增'
      width="500"
      :before-close="handleClose"
      center
  >
    <div style="width: 100% ; border-top: #6b778c 1px solid;margin-bottom: 50px"></div>
      <span>
        <el-form :model="form" label-width="auto" style="max-width: 250px;font-size: 20px">
    <el-form-item  label="题目:">
      <el-input v-model="form.audioTitle"  style="width: 400px" />
    </el-form-item>
          <el-form-item v-model="form.audio"  label="音频:">
        <div>
          <label class="upload-button" for="fileInput">
      <span  v-show="!isfile">选择音频文件</span>
      <span v-show="isfile">已选择音频文件</span>
     <input type="file" @change="handleFileUpload" accept="audio/*" />
    </label>
<!--              <div v-if="audioBase64">-->

<!--      <p>Audio Preview:</p>-->
<!--      <audio :src="audioBase64" controls></audio>-->
<!--    </div>-->
  </div>
    </el-form-item>
     <el-form-item >
      <el-button @click="submit()" style="border: solid 1px #4285F4;border-radius: 20px;width: 200px;color: #4285F4;margin-left: 200px">提交</el-button>
    </el-form-item>
  </el-form>
      </span>
  </el-dialog>

</template>

<style scoped>
.product-box {
  border: 1px solid #ccc;
  padding: 16px;
  margin: 16px 0;
  width: 200px;
  height: 250px;
  background-image: url('@/image/audio1.png');
 background-repeat: no-repeat;
  background-size: 100% 100%;
}
.scrollbar-demo-item {
  display: flex;
 align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.product-list {
  max-width: 1600px;
  padding: 20px;
}

.product-grid {
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  gap: 30px;       /* 子元素之间的间距 */
}

.product-box {
  width: 185px;    /* 固定宽度 */
  height: 220px;   /* 固定高度 */
  box-sizing: border-box; /* 包括内边距和边框在内计算元素的总宽度和高度 */
  border: 1px solid #ccc;
  padding: 16px;
  text-align: center; /* 可选：使文本居中 */
  overflow: hidden;   /* 可选：隐藏超出盒子大小的内容 */
}
@media (max-width: 1760px) { /* 稍微大一点以确保8个盒子能在一行内（考虑边框、内边距等） */
  .product-grid {
    flex-wrap: wrap; /* 允许换行 */
  }

  .product-box {
    /* 你可以在这里设置更小的宽度或百分比宽度，以适应更小的屏幕 */
    /* 例如：width: calc(25% - 20px); 在四列布局时使用 */
  }
}
.product-box:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 鼠标经过时的阴影效果 */
}
.upload-button {
  display: inline-block;
//padding: 10px 10px;
  width: 150px;
  height: 35px;
  font-size: 14px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
  overflow: hidden;
  text-align: center;
}

.upload-button span {
  display: block;
}

.upload-button input[type="file"] {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-button:hover {
  background-color: #0056b3;
}
</style>